<template>
  <div v-loading="pageLoading" class="home_league">
    <header class="game_modal_header">机构排行榜</header>
    <div class="schedule_content modal_shadow">
      <el-row class="subtotal gl_pb_15">
        <el-col :span="24">
          <el-radio-group v-model="topListType" size="small" @change="changeTopList">
            <el-radio-button label="">总榜</el-radio-button>
            <el-radio-button label="Competitive">竞技榜</el-radio-button>
            <el-radio-button label="NoneCompetitive">品势榜</el-radio-button>
          </el-radio-group>
        </el-col>
      </el-row>

      <div class="gl_pb_15">
        <el-form :model="qo" size="small" label-width="70px">
          <el-row :gutter="30">
            <el-col :span="6">
              <el-form-item label="项目">
                <el-select v-model="qo.CategoryId" style="width:100%" placeholder="请选择项目" @change="getPageList()">
                  <el-option v-for="(item, index) in categoryFilterList" :key="index" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="机构名称">
                <el-input v-model="qo.Keyword" placeholder="请输入内容" @change="getPageList()" />
              </el-form-item>
            </el-col>
            <el-col :offset="6" :span="6" align="right">
              <el-form-item>
                <div class="gl_pr_5">
                  <template v-for="(item, index) in scoreShow">
                    <span :key="index" class="score_change" :class="{'active': index === activeScore}" @click="changeTableColumn(index)">{{ item.name }}</span>
                    <span v-if="index !== scoreShow.length - 1" :key="'-' + index"> / </span>
                  </template>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table :key="topListType" v-loading="tableLoading" :data="tableData" stripe size="small" style="width: 100%" @sort-change="onSortChange">
          <el-table-column prop="name" label="机构名称" align="left" min-width="160">
            <template slot-scope="scope">
              <div class="agency_wrap gl_clear">
                <div class="agency_photo gl_mr_10">
                  <img :src="getStaticFileUrl(scope.row.photoUrl)" @error="errorPhoto">
                </div>
                <span>{{ scope.row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="organization" label="机构地区" align="left" min-width="120" />
          <el-table-column sortable="custom" label="金牌" align="center" :sort-orders="['ascending','descending', null]" :default-sort="{order: 'null'}" prop="gold">
            <template slot="header">
              <img style="padding-left:22px;vertical-align:middle;" src="@/assets/images/league/gold.png">
            </template>
            <template slot-scope="scope">
              <span>{{ scope.row.subRankList[0] ? scope.row.subRankList[0].subRankCount : '' }}</span>
            </template>
          </el-table-column>
          <el-table-column sortable="custom" label="银牌" align="center" :sort-orders="['ascending','descending', null]" :default-sort="{order: 'null'}" prop="silver">
            <template slot="header">
              <img style="padding-left:22px;vertical-align:middle;" src="@/assets/images/league/silver.png">
            </template>
            <template slot-scope="scope">
              <span>{{ scope.row.subRankList[1] ? scope.row.subRankList[1].subRankCount : '' }}</span>
            </template>
          </el-table-column>
          <el-table-column sortable="custom" label="铜牌" align="center" :sort-orders="['ascending','descending', null]" :default-sort="{order: 'null'}" prop="bronze">
            <template slot="header">
              <img style="padding-left:22px;vertical-align:middle;" src="@/assets/images/league/bronze.png">
            </template>
            <template slot-scope="scope">
              <span>{{ scope.row.subRankList[2] ? scope.row.subRankList[2].subRankCount : '' }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="activeScore === 0" prop="finalPoints" sortable label="总分" align="center" />
          <el-table-column v-if="activeScore === 1" prop="unitPoints" sortable label="场次分" align="center" />
          <el-table-column v-if="activeScore === 2" prop="rankPoints" sortable label="名次分" align="center" />
        </el-table>
      </div>

      <!-- 分页 -->
      <el-row style="text-align: center;">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="qo.MaxResultCount"
          :current-page="qo.Page"
          @size-change="changePageSize"
          @current-change="changePage"
        />
      </el-row>
    </div>
  </div>
</template>

<script>
import {
  api_GET_EventsManagementEventResultUnifiedPointRankList,
  api_GET_EventsManagementCategory // 获取项目类别列表
} from '@/extend/api/gameswaggerApi/app';

import {
  Api_GET_EventsManagementEventResultUnifiedPointRankListQO
} from '@/lib/form/game/swaggerForm';

import defaultPhoto from '@/assets/images/face_default.png';

export default {
  props: {
    gameInfo: {
      type: Object,
      default () {
        return {};
      }
    }
  },
  data () {
    return {
      defaultPhoto: defaultPhoto, // 默认照片
      topListType: '', // 榜单类型
      pageLoading: false,
      tableLoading: false,
      tableData: [],
      total: 0,
      qo: new Api_GET_EventsManagementEventResultUnifiedPointRankListQO(),
      categoryList: [],
      scoreShow: [
        {
          name: '总分'
        },
        {
          name: '场次分'
        },
        {
          name: '名次分'
        }
      ],
      activeScore: 0
    };
  },
  computed: {
    categoryFilterList () {
      if (this.topListType) {
        const _list = this.categoryList.filter(item => item.eventTypeCode === this.topListType);
        _list.unshift({
          name: '全部',
          id: null
        });
        return _list;
      } else {
        return this.categoryList;
      }
    }
  },
  watch: {
    gameInfo: {
      immediate: true,
      deep: true,
      handler(val) {
        if (val.id) {
          this.getPageList();
          this.getCategoryList({
            CompetitionId: this.gameInfo.id
          });
        }
      }
    }
  },
  methods: {
    changeTopList () {
      this.qo.CategoryId = null;
      this.getPageList();
    },
    // 获取页面数据
    getPageList (page) {
      const _qo = JSON.parse(JSON.stringify(this.qo));
      _qo.Page = page || 1;
      this.qo.Page = _qo.Page;
      _qo.SkipCount = (_qo.Page - 1) * _qo.MaxResultCount;
      _qo.CompetitionId = this.gameInfo.id;
      _qo.Type = 'Delegation';
      _qo.EventTypeCode = this.topListType;
      _qo.IncludeFinal = true;
      _qo.IncludeSubRank = true;
      console.log('_qo: ', _qo);
      this.apiRankList(_qo);
    },
    // 获取大项列表
    getCategoryList (qo) {
      api_GET_EventsManagementCategory(qo)
        .then(
          res => {
            console.log(res);
            if (res) {
              const _list = res.items || [];
              _list.unshift({
                name: '全部',
                id: null
              });
              this.categoryList = _list;
            }
          }
        );
    },
    changeTableColumn (index) {
      this.activeScore = index;
    },
    // UnifiedPointRankList
    apiRankList(qo) {
      this.tableLoading = true;
      api_GET_EventsManagementEventResultUnifiedPointRankList(qo)
        .then(
          res => {
            this.tableLoading = false;
            this.total = res.totalCount;
            res.items.forEach((item, index) => {
              item.$order = index;
            });
            this.tableData = res.items;
            console.log(res);
          }
        )
        .catch(
          error => {
            this.tableLoading = false;
            console.log(error);
          }
        );
    },
    onSortChange({ prop, order }) {
      this.tableData.sort(this.compare(prop, order));
    },
    compare (prop, order) {
      return function (a, b) {
        let _a, _b;
        if (prop === 'gold') {
          _a = a.subRankList[0].subRankCount;
          _b = b.subRankList[0].subRankCount;
        }
        if (prop === 'silver') {
          _a = a.subRankList[1].subRankCount;
          _b = b.subRankList[1].subRankCount;
        }
        if (prop === 'bronze') {
          _a = a.subRankList[2].subRankCount;
          _b = b.subRankList[2].subRankCount;
        }

        if (order === 'ascending') {
          if (_a < _b) { return -1; }
          if (_a > _b) { return 1; }
          return 0;
        } else if (order === 'descending') {
          if (_a > _b) { return -1; }
          if (_a < _b) { return 1; }
          return 0;
        } else {
          _a = a.$order;
          _b = b.$order;
          if (_a < _b) { return -1; }
          if (_a > _b) { return 1; }
          return 0;
        }
      };
    },
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    errorPhoto() {
      const img = event.srcElement;
      img.src = this.defaultPhoto;
      img.onerror = null;
    },
    // 分页
    changePage(page) {
      this.getPageList(page);
    },
    changePageSize(pagesize) {
      this.qo.MaxResultCount = pagesize;
      this.getPageList();
    }
  }
};
</script>

<style>
  .score_change {
    font-size: 14px;
    font-weight: 400;
    line-height: 16px;
    white-space: nowrap;
    color: #606266;
    cursor: pointer;
  }
  .score_change.active {
    font-weight: bold;
    color: #1890ff;
  }
</style>
